import axios from 'axios'

export default {
  namespaced: true,
  state () {
    return {
      list: []

    }
  },
  // 修改state数据
  mutations: {
    // 修改定义list的数据---将请求的购物车列表数据赋给空数组list
    setList (state, list) {
      state.list = list
    },
    // 拿到actions中传过来的数据，找到对应的数组对象，修改数量
    changeCounttwo (state, payload) {
      const lists = state.list.find(item => item.id === payload.id)
      lists.count = payload.count
    }
  },
  // 异步代码
  actions: {
    // 获取购物车商品列表
    async getList (ctx) {
      const res = await axios.get('http://localhost:3000/cart')
      // console.log(res)
      ctx.commit('setList', res.data)
    },
    // 修改商品数量，通过发送请求，payload形参
    async changeCount (ctx, payload) {
      // patch请求，拼接路径，携带修改后的商品数量
      await axios.patch('http://localhost:3000/cart/' + payload.id, {
        count: payload.count
      })
      // console.log(res)
      // 修改state中的数据只能通过mutations修改，所以通过ctx.commit把参数传给changeCounttwo执行相关操作
      ctx.commit('changeCounttwo', payload)
    }
  },
  getters: {
    // 获取商品总数
    countTotal (state) {
      return state.list.reduce((num, item) => num + item.count, 0)
    },
    // 获取商品总价
    countPrice (state) {
      return state.list.reduce((num, item) => num + item.count * item.price, 0)
    }
  }
}
